package com.tg.paw.oms.mq.consumer;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.rabbitmq.client.Channel;
import com.tg.paw.common.model.MessageData;
import com.tg.paw.common.mq.entity.MqMessage;
import com.tg.paw.common.mq.service.IMqMessageService;
import com.tg.paw.oms.constants.MqConstants;
import com.tg.paw.oms.enums.OmsMessageEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * @author Rubble
 * @date 2020/6/18
 */
@Slf4j
@Component
public class OrderConsumer {

    @Autowired
    private IMqMessageService mqMessageService;


    /**
     * // @RabbitListener(queues = MqConstants.ORDER_UMS_PAW_QUEUE)
     *
     * @param messageBody
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(MqConstants.ORDER_UMS_PAW_QUEUE),
            key = MqConstants.ORDER_UMS_PAW_ROUTING_KEY,
            exchange = @Exchange(value = MqConstants.DIRECT_EXCHANGE)
    ))
    @RabbitHandler
    public void onMessage(String messageBody, Message message, Channel channel) throws IOException {
        log.info("[onMessage][线程编号:{} Queue:{} 消息内容：{}]", Thread.currentThread().getId(),
                message.getMessageProperties().getConsumerQueue(), messageBody);
        Type type = new TypeReference<MessageData<String>>() {}.getType();
        MessageData<String> messageData = JSONObject.parseObject(messageBody, type);
        try{
            int random = RandomUtil.randomInt(10);
            if(random>=8){
                int i=1/0;
            }
        }catch (Exception e){
            // 保存失败的消息 保存到DB 或发送到指定的队列
            String uuid = messageData.getUuid();;
            MqMessage mqMessage = new MqMessage(uuid,MqConstants.VIRTUAL_HOST,MqConstants.DIRECT_EXCHANGE,
                    MqConstants.ORDER_UMS_PAW_QUEUE, MqConstants.ORDER_UMS_PAW_ROUTING_KEY,
                    OmsMessageEnum.ORDER_UMS_PAW_ROUTING_KEY.getValue(),messageBody,e.getMessage(),OrderConsumer.class.getName());
            mqMessageService.save(mqMessage);
            log.error("OrderConsumer error. message: {} ",messageBody, e);
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

}
